﻿<template>
  <div class="jnpf-content-wrapper">
    <div class="jnpf-content-wrapper-center">
      <div class="jnpf-content-wrapper-search-box" v-if="columnData.searchList?.length">
        <BasicForm ref="basicFormRef" @register="registerSearchForm" :schemas="searchSchemas"
          :columnOptions="columnOptions" @advanced-change="redoHeight" @submit="handleSearchSubmit"
          @reset="handleSearchReset" @add-field="handleSetRelationData" class="search-form">
        </BasicForm>

        <div class="a-box-info">
          <a-row :gutter="24">
            <a-col :span="18">
              <a-form :label-col="{ style: { width: '80px' } }">
                <a-row :gutter="24">
                  <a-col :span="formSpan">
                    <a-form-item name="customerCode">
                      <JnpfInput v-model:value="dataForm.customerCode" readonly addonBefore="用户编号" allowClear
                        :style="{ width: '100%' }" />
                    </a-form-item>
                  </a-col>

                  <a-col :span="formSpan">
                    <a-form-item name="customerName">
                      <JnpfInput v-model:value="dataForm.customerName" readonly addonBefore="用户姓名" allowClear
                        :style="{ width: '100%' }" />
                    </a-form-item>
                  </a-col>

                  <a-col :span="formSpan">
                    <a-form-item name="factoryNum">
                      <JnpfInput v-model:value="dataForm.factoryNum" readonly addonBefore="水表编号" allowClear
                        :style="{ width: '100%' }" />
                    </a-form-item>
                  </a-col>

                  <a-col :span="6">
                    <a-form-item name="address">
                      <JnpfInput v-model:value="dataForm.address" readonly addonBefore="地址"
                        :style="{ width: '100%', color: 'red' }" />
                    </a-form-item>
                  </a-col>


                  <a-col :span="0">
                    <a-form-item name="actualAmount">
                      <JnpfInput v-model:value="dataForm.actualAmount" readonly addonBefore="综合水费"
                        :style="{ width: '100%' }" />
                    </a-form-item>
                  </a-col>
                  <a-col :span="0">
                    <a-form-item name="overdueAmount">
                      <JnpfInput v-model:value="dataForm.overdueAmount" readonly addonBefore="违约金额"
                        :style="{ width: '100%' }" />
                    </a-form-item>
                  </a-col>

                  <a-col :span="formSpan">
                    <a-form-item name="perviousBalance" class="labelRed" label="上次余额" :colon="false">
                      <a-input v-model:value="dataForm.perviousBalance" readonly></a-input>
                      <!-- <JnpfInput v-model:value="dataForm.perviousBalance" readonly addonBefore="上次余额"
                      :style="{ width: '100%' }" /> -->
                    </a-form-item>
                  </a-col>

                  <a-col :span="formSpan">
                    <a-form-item name="arrears" class="labelRed" label="合计金额" :colon="false">
                      <a-input v-model:value="dataForm.arrears" readonly></a-input>

                      <!-- <JnpfInput v-model:value="dataForm.arrears" class="labelRed" readonly addonBefore="合计金额"
                      :style="{ width: '100%' }" /> -->
                    </a-form-item>
                  </a-col>

                  <a-col :span="formSpan">
                    <a-form-item name="receivableAmount" label="应收金额" class="labelRed" :colon="false">
                      <a-input v-model:value="dataForm.receivableAmount" readonly></a-input>
                      <!-- 
                    <JnpfInput v-model:value="dataForm.receivableAmount" readonly addonBefore="应收金额"
                    class="custom-input"  /> -->
                    </a-form-item>
                  </a-col>

                  <a-col :span="6">
                    <a-form-item name="comment">
                      <JnpfInput v-model:value="dataForm.comment" readonly addonBefore="备注"
                        :style="{ width: '100%' }" />
                    </a-form-item>
                  </a-col>

                </a-row>
              </a-form>
            </a-col>

            <a-col :span="6">
              <a-tabs size="small"> </a-tabs>
            </a-col>
          </a-row>
        </div>
      </div>
      <div class="a-box-button">
        <template v-for="(item, i) in columnData.btnsList">
          <a-button type="primary" style="margin-right: 10px;" :preIcon="item.icon"
            v-if="isPreview || !columnData.useBtnPermission || hasBtnP('btn_' + item.value)" :key="item.value"
            @click="headBtnsHandle(item.value, item)">
            {{ item.label }}
          </a-button>
        </template>
      </div>

      <div class="jnpf-content-wrapper-content">
        <div class="tabs">
          <a-tabs type="" tabPosition="top" class="mb-20" @change="handleSwitch" :destroy-on-hide="true">
            <a-tab-pane key="main" tab="欠费记录">
              <BasicTable @register="registerTable" v-bind="getTableBindValue" ref="tableRef"
                @columns-change="handleColumnChange">
                <template #bodyCell="{ column, record, index }">
                  <template v-if="column.flag === 'INDEX'">
                    <span>{{ index + 1 }}</span>
                  </template>
                  <template v-if="columnData.type === 4">
                    <template v-if="record.rowEdit">
                      <template v-if="column.jnpfKey === 'inputNumber'">
                        <jnpf-input-number v-model:value="record[column.prop]" :placeholder="column.placeholder"
                          :min="column.min" :max="column.max" :step="column.step" :controls="column.controls"
                          :addonBefore="column.addonBefore" :addonAfter="column.addonAfter"
                          :precision="column.precision" :thousands="column.thousands" :disabled="column.disabled" />
                      </template>
                      <template v-else-if="column.jnpfKey === 'calculate'">
                        <jnpf-calculate v-model:value="record[column.prop]" :isStorage="column.isStorage"
                          :precision="column.precision" :thousands="column.thousands" detailed />
                      </template>
                      <template v-else-if="['rate', 'slider'].includes(column.jnpfKey)">
                        <a-input-number v-model:value="record[column.prop]" placeholder="请输入"
                          :disabled="column.disabled" />
                      </template>
                      <template v-else-if="column.jnpfKey === 'switch'">
                        <jnpf-switch v-model:value="record[column.prop]" :disabled="column.disabled" />
                      </template>
                      <template v-else-if="column.jnpfKey === 'timePicker'">
                        <jnpf-time-picker v-model:value="record[column.prop]" :format="column.format"
                          :startTime="column.startTime" :endTime="column.endTime" :placeholder="column.placeholder"
                          :allowClear="column.clearable" :disabled="column.disabled" />
                      </template>
                      <template v-else-if="column.jnpfKey === 'datePicker'">
                        <jnpf-date-picker v-model:value="record[column.prop]" :format="column.format"
                          :startTime="column.startTime" :endTime="column.endTime" :allowClear="column.clearable"
                          :placeholder="column.placeholder" :disabled="column.disabled" />
                      </template>
                      <template v-else-if="column.jnpfKey === 'organizeSelect'">
                        <jnpf-organize-select v-model:value="record[column.prop]" :placeholder="column.placeholder"
                          :multiple="column.multiple" :allowClear="column.clearable" :disabled="column.disabled"
                          :selectType="column.selectType" :ableIds="column.ableIds" />
                      </template>
                      <template v-else-if="column.jnpfKey === 'depSelect'">
                        <jnpf-dep-select v-model:value="record[column.prop]" :placeholder="column.placeholder"
                          :multiple="column.multiple" :allowClear="column.clearable" :disabled="column.disabled"
                          :selectType="column.selectType" :ableIds="column.ableIds" />
                      </template>
                      <template v-else-if="column.jnpfKey === 'roleSelect'">
                        <jnpf-role-select v-model:value="record[column.prop]" :placeholder="column.placeholder"
                          :multiple="column.multiple" :allowClear="column.clearable" :disabled="column.disabled"
                          :selectType="column.selectType" :ableIds="column.ableIds" />
                      </template>
                      <template v-else-if="column.jnpfKey === 'groupSelect'">
                        <jnpf-group-select v-model:value="record[column.prop]" :placeholder="column.placeholder"
                          :multiple="column.multiple" :allowClear="column.clearable" :disabled="column.disabled"
                          :selectType="column.selectType" :ableIds="column.ableIds" />
                      </template>
                      <template v-else-if="column.jnpfKey === 'posSelect'">
                        <jnpf-pos-select v-model:value="record[column.prop]" :placeholder="column.placeholder"
                          :multiple="column.multiple" :allowClear="column.clearable" :disabled="column.disabled"
                          :selectType="column.selectType" :ableIds="column.ableIds" />
                      </template>
                      <template v-else-if="column.jnpfKey === 'userSelect'">
                        <jnpf-user-select v-model:value="record[column.prop]" :placeholder="column.placeholder"
                          :multiple="column.multiple" :allowClear="column.clearable" :disabled="column.disabled"
                          :selectType="['all', 'custom'].includes(column.selectType) ? column.selectType : 'all'"
                          :ableIds="column.ableIds" />
                      </template>
                      <template v-else-if="column.jnpfKey === 'usersSelect'">
                        <jnpf-users-select v-model:value="record[column.prop]" :placeholder="column.placeholder"
                          :multiple="column.multiple" :allowClear="column.clearable" :disabled="column.disabled"
                          :selectType="column.selectType" :ableIds="column.ableIds" />
                      </template>
                      <template v-else-if="column.jnpfKey === 'areaSelect'">
                        <jnpf-area-select v-model:value="record[column.prop]" :level="column.level"
                          :placeholder="column.placeholder" :multiple="column.multiple" :allowClear="column.clearable"
                          :disabled="column.disabled" />
                      </template>
                      <template v-else-if="['select', 'radio', 'checkbox'].includes(column.jnpfKey)">
                        <jnpf-select v-model:value="record[column.prop]" :placeholder="column.placeholder"
                          :multiple="column.multiple || column.jnpfKey === 'checkbox'"
                          :allowClear="column.clearable || ['radio', 'checkbox'].includes(column.jnpfKey)"
                          :showSearch="column.filterable" :disabled="column.disabled" :options="column.options"
                          :fieldNames="column.props" />
                      </template>
                      <template v-else-if="column.jnpfKey === 'cascader'">
                        <jnpf-cascader v-model:value="record[column.prop]" :placeholder="column.placeholder"
                          :multiple="column.multiple" :allowClear="column.clearable" :showSearch="column.filterable"
                          :disabled="column.disabled" :options="column.options" :fieldNames="column.props"
                          :showAllLevels="column.showAllLevels" />
                      </template>
                      <template v-else-if="column.jnpfKey === 'treeSelect'">
                        <jnpf-tree-select v-model:value="record[column.prop]" :placeholder="column.placeholder"
                          :multiple="column.multiple" :allowClear="column.clearable" :showSearch="column.filterable"
                          :disabled="column.disabled" :options="column.options" :fieldNames="column.props" />
                      </template>
                      <template v-else-if="column.jnpfKey === 'relationForm'">
                        <jnpf-relation-form v-model:value="record[column.prop]" :placeholder="column.placeholder"
                          :allowClear="column.clearable" :disabled="column.disabled" :modelId="column.modelId"
                          :columnOptions="column.columnOptions" :relationField="column.relationField"
                          :hasPage="column.hasPage" :pageSize="column.pageSize" :popupType="column.popupType"
                          :popupTitle="column.popupTitle" :popupWidth="column.popupWidth" />
                      </template>
                      <template v-else-if="column.jnpfKey === 'popupSelect' || column.jnpfKey === 'popupTableSelect'">
                        <jnpf-popup-select v-model:value="record[column.prop]" :placeholder="column.placeholder"
                          :multiple="column.multiple" :allowClear="column.clearable" :disabled="column.disabled"
                          :interfaceId="column.interfaceId" :templateJson="column.templateJson"
                          :columnOptions="column.columnOptions" :propsValue="column.propsValue"
                          :relationField="column.relationField" :hasPage="column.hasPage" :pageSize="column.pageSize"
                          :popupType="column.popupType" :popupTitle="column.popupTitle"
                          :popupWidth="column.popupWidth" />
                      </template>
                      <template v-else-if="column.jnpfKey === 'autoComplete'">
                        <jnpf-auto-complete v-model:value="record[column.prop]" :placeholder="column.placeholder"
                          :allowClear="column.clearable" :disabled="column.disabled" :interfaceId="column.interfaceId"
                          :relationField="column.relationField" :templateJson="column.templateJson"
                          :total="column.total" />
                      </template>
                      <template v-else-if="['input', 'textarea'].includes(column.jnpfKey)">
                        <jnpf-input v-model:value="record[column.prop]" :placeholder="column.placeholder"
                          :allowClear="column.clearable" :disabled="column.disabled" :readonly="column.readonly"
                          :prefixIcon="column.prefixIcon" :suffixIcon="column.suffixIcon"
                          :addonBefore="column.addonBefore" :addonAfter="column.addonAfter"
                          :maxlength="column.maxlength" :showPassword="column.showPassword">
                        </jnpf-input>
                      </template>
                      <template v-else-if="systemComponentsList.includes(column.jnpfKey)">
                        {{ record[column.prop + '_name'] || record[column.prop] }}
                      </template>
                      <template v-else>
                        {{ record[column.prop] }}
                      </template>
                    </template>
                    <template v-else>
                      <template v-if="column.jnpfKey === 'inputNumber'">
                        <jnpf-input-number v-model:value="record[column.prop + '_name']" :precision="column.precision"
                          :thousands="column.thousands" disabled detailed />
                      </template>
                      <template v-else-if="column.jnpfKey === 'calculate'">
                        <jnpf-calculate v-model:value="record[column.prop + '_name']" :isStorage="column.isStorage"
                          :precision="column.precision" :thousands="column.thousands" detailed />
                      </template>
                      <template v-else-if="column.jnpfKey === 'relationForm'">
                        <!-- <p class="link-text" @click="toDetail(column.modelId, record[`${column.prop}_id`])">
                    {{ record[column.prop + '_name'] || record[column.prop] }}
                  </p> -->
                        <!-- modify by harry 关联表单不需要特殊显示 -->
                        {{ record[column.prop + '_name'] || record[column.prop] }}
                      </template>
                      <template v-else>
                        {{ record[column.prop + '_name'] || record[column.prop] }}
                      </template>
                    </template>
                  </template>
                  <template v-else>
                    <template v-if="column.jnpfKey === 'relationForm'">
                      {{ record[column.prop] }}
                    </template>
                    <template v-if="column.jnpfKey === 'inputNumber'">
                      <jnpf-input-number v-model:value="record[column.prop]" :precision="column.precision"
                        :thousands="column.thousands" disabled detailed />
                    </template>
                    <template v-if="column.jnpfKey === 'calculate'">
                      <jnpf-calculate v-model:value="record[column.prop]" :isStorage="column.isStorage"
                        :precision="column.precision" :thousands="column.thousands" detailed />
                    </template>
                  </template>
                </template>
                <template #summary v-if="columnData.showSummary && [1, 2, 4].includes(columnData.type)">
                  <a-table-summary fixed>
                    <a-table-summary-row>
                      <template v-if="state.hasBatchBtn">
                        <a-table-summary-cell :index="0" :col-span="2">合计</a-table-summary-cell>
                        <a-table-summary-cell :index="1" :col-span="0"></a-table-summary-cell>
                        <a-table-summary-cell v-for="(item, index) in getColumnSum" :key="index" :index="index + 2"
                          :align="getSummaryCellAlign(index)">
                          {{ item }}
                        </a-table-summary-cell>
                        <a-table-summary-cell :index="getColumnSum.length + 2"></a-table-summary-cell>
                      </template>
                      <template v-else>
                        <a-table-summary-cell :index="0">合计</a-table-summary-cell>
                        <a-table-summary-cell v-for="(item, index) in getColumnSum" :key="index" :index="index + 1"
                          :align="getSummaryCellAlign(index)">
                          {{ item }}
                        </a-table-summary-cell>
                        <a-table-summary-cell :index="getColumnSum.length + 1"></a-table-summary-cell>
                      </template>
                    </a-table-summary-row>
                  </a-table-summary>
                </template>
              </BasicTable>
            </a-tab-pane>
            <a-tab-pane v-for="item in tabArr" :key="item.f_id" :tab="item.f_full_name" forceRender
              :destroy-on-hide="true">
            </a-tab-pane>
          </a-tabs>
        </div>
        <a-table :columns="columns" :data-source="tableData"
          :scroll="{ y: 'calc(100vh - 580px)', x: columns.length * 90 }" :loading="loading"></a-table>
      </div>
    </div>
    <Form ref="formRef" @reload="reload" />
    <Detail ref="detailRef" />
    <CandidateModal @register="registerCandidate" @confirm="submitCandidate" />
    <FlowParser @register="registerFlowParser" @reload="reload" />
    <ExportModal @register="registerExportModal" @download="handleDownload" />
    <ImportModal @register="registerImportModal" @reload="reload" />
    <SuperQueryModal @register="registerSuperQueryModal" @superQuery="handleSuperQuery" />
    <CustomForm ref="customFormRef" />
    <CustomBatchForm ref="customBatchFormRef" />
    <PrintSelect @register="registerPrintSelect" @change="handleShowBrowse" />
    <PrintBrowse @register="registerPrintBrowse" />
  </div>
</template>

<script lang="ts" setup>
import { getModelList, exportModel, delModel, batchDelete, getConfigData, createModel, updateModel, getModelInfo } from '/@/api/onlineDev/visualDev';
import { create as createFlowForm, update as updateFlowForm } from '/@/api/workFlow/workFlowForm';
import { getCandidates } from '/@/api/workFlow/flowBefore';
import { getDataInterfaceRes } from '/@/api/systemData/dataInterface';
import { ref, reactive, onMounted, toRefs, computed, unref, nextTick, toRaw } from 'vue';
import { getFlowList } from '/@/api/workFlow/flowEngine';
import { useMessage } from '/@/hooks/web/useMessage';
import { useI18n } from '/@/hooks/web/useI18n';
import { useOrganizeStore } from '/@/store/modules/organize';
import { useUserStore } from '/@/store/modules/user';
import { useBaseStore } from '/@/store/modules/base';
import { BasicModal, useModal } from '/@/components/Modal';
import { usePopup } from '/@/components/Popup';
import { ScrollContainer } from '/@/components/Container';
import { BasicLeftTree, TreeActionType } from '/@/components/Tree';
import { BasicForm, useForm } from '/@/components/Form';
import { BasicTable, useTable, TableAction, ActionItem, TableActionType } from '/@/components/Table';

import Form from '/@/views/common/dynamicModel/list//Form.vue';
import CustomForm from '/@/views/common/dynamicModel/list//CustomForm.vue';
import CustomBatchForm from '/@/views/common/dynamicModel/list//CustomBatchForm.vue';
import Detail from '/@/views/common/dynamicModel/list/detail/index.vue';
import ChildTableColumn from '/@/views/common/dynamicModel/list/ChildTableColumn.vue';

import FlowParser from '/@/views/workFlow/components/FlowParser.vue';
import CandidateModal from '/@/views/workFlow/components/modal/CandidateModal.vue';
import { ExportModal, ImportModal, SuperQueryModal } from '/@/components/CommonModal';
import { downloadByUrl } from '/@/utils/file/download';
import { useRoute } from 'vue-router';
import { getScriptFunc, onlineUtils, getDateTimeUnit, getTimeUnit, thousandsFormat } from '/@/utils/jnpf';
import { FilterOutlined } from '@ant-design/icons-vue';
import { getSearchFormSchemas } from '/@/components/FormGenerator/src/helper/transform';
import { dyOptionsList, systemComponentsList } from '/@/components/FormGenerator/src/helper/config';
import { JnpfRelationForm } from '/@/components/Jnpf';
import { cloneDeep } from 'lodash-es';
import PrintSelect from '/@/components/PrintDesign/printSelect/index.vue';
import PrintBrowse from '/@/components/PrintDesign/printBrowse/index.vue';
import dayjs from 'dayjs';
import { usePermission } from '/@/hooks/web/usePermission';

interface State {
  flowList: any[];
  config: any;
  columnData: any;
  formConf: any;
  hasBatchBtn: boolean;
  columnBtnsList: any[];
  customBtnsList: any[];
  columnOptions: any[];
  treeFieldNames: any;
  leftTreeData: any[];
  leftTreeLoading: boolean;
  treeActiveId: string;
  treeActiveNodePath: any;
  columns: any[];
  complexColumns: any[];
  childColumnList: any[];
  exportList: any[];
  cacheList: any[];
  currFlow: any;
  isCustomCopy: boolean;
  candidateType: number;
  currRow: any;
  workFlowFormData: any;
  expandObj: any;
  columnSettingList: any[];
  searchSchemas: any[];
  treeRelationObj: any;
  treeQueryJson: any;
  customRow: any;
  customCell: any;
}

const dataForm: any = reactive({
  nameCode: '',
  customerCode: '',
  customerName: '',
  mobilePhone: '',
  factoryNum: '',
  address: '',
  addicationDecimal1Flag: '',
  overdueAmount: null,
  arrears: null,
  perviousBalance: null,
  comment: '',
  receivableAmount: null,
});
const formSpan: number = 6;
const opearSpan: number = 12;

interface TabType {
  f_id: string;
  f_full_name: string;
}

const tabArr = ref<TabType[]>();
const columns = ref<any>([]);
const tableData = ref<any>([]);
const keyArr = 'abcdefghijklmnopqrstuvwxyz'.split('');
const loading = ref<Boolean>(true);

let defaultValue: any = 0;
let typeId: any = 0;
let customerID: any;

import { getType, getListApi } from './helper/api';
// 获取表格数据
const getData = (id, data) => {
  getListApi(id, data).then(res => {
    const arr = res.data;

    let columnTemp: any = [];
    const tables = arr.map((item, index) => {
      const arr = Object.keys(item);
      let field = {};
      field[keyArr[index]] = item[index];

      columnTemp = arr.map((_item, _index) => {
        field[keyArr[_index]] = item[_item];
        return {
          title: _item,
          dataIndex: keyArr[_index],
          customHeaderCell: function () {
            return {
              style: {
                'white-space': 'nowrap',
              },
            };
          }
        };
      });

      return field;
    });
    columns.value = columnTemp;
    tableData.value = tables;
    loading.value = false;
  });
};

// 切换标签
const handleSwitch = (e: string) => {
  typeId = e;
  loading.value = true;
  tableData.value = [];
  const data = {
    origin: 'preview',
    tenantId: 'default',
    paramList: [
      {
        dataType: 'varchar',
        defaultValue,
        field: 'CustomerID',
        fieldName: '用户ID',
        id: 'bd01da',
        required: '1',
        source: null,
      },
    ],
  };
  getData(typeId, data);
};

const emit = defineEmits(['register', 'reload']);
const props = defineProps(['config', 'modelId', 'isPreview']);
const route = useRoute();
const { hasBtnP } = usePermission();
const { createMessage, createConfirm } = useMessage();
const { t } = useI18n();
const organizeStore = useOrganizeStore();
const userStore = useUserStore();
const baseStore = useBaseStore();
const [registerFlowParser, { openPopup: openFlowParser }] = usePopup();
const [registerExportModal, { openModal: openExportModal, closeModal: closeExportModal, setModalProps: setExportModalProps }] = useModal();
const [registerImportModal, { openModal: openImportModal }] = useModal();
const [registerSuperQueryModal, { openModal: openSuperQuery }] = useModal();
const [registerFlowListModal, { openModal: openFlowListModal, closeModal: closeFlowListModal }] = useModal();
const [registerCandidate, { openModal: openCandidateModal, closeModal: closeCandidateModal }] = useModal();
const [registerPrintSelect, { openModal: openPrintSelect }] = useModal();
const [registerPrintBrowse, { openModal: openPrintBrowse }] = useModal();
const leftTreeRef = ref<Nullable<TreeActionType>>(null);
const formRef = ref<any>(null);
const customFormRef = ref<any>(null);
const customBatchFormRef = ref<any>(null);

const basicFormRef = ref(null);

const tableRef = ref<Nullable<TableActionType>>(null);
const detailRef = ref<any>(null);
const searchInfo = reactive({
  modelId: '',
  menuId: '',
  queryJson: '',
  superQueryJson: '',
});
const state = reactive<State>({
  flowList: [],
  config: {},
  columnData: {},
  formConf: {},
  hasBatchBtn: false,
  columnBtnsList: [],
  customBtnsList: [],
  columnOptions: [],
  treeFieldNames: {
    children: 'children',
    title: 'fullName',
    key: 'id',
    isLeaf: 'isLeaf',
  },
  leftTreeData: [],
  leftTreeLoading: false,
  treeActiveId: '',
  treeActiveNodePath: [],
  columns: [],
  complexColumns: [], // 复杂表头
  childColumnList: [],
  exportList: [],
  cacheList: [],
  currFlow: {},
  isCustomCopy: false,
  candidateType: 1,
  currRow: {},
  workFlowFormData: {},
  expandObj: {},
  columnSettingList: [],
  searchSchemas: [],
  treeRelationObj: null,
  treeQueryJson: {},
  customRow: null,
  customCell: null,
});
const { columnData, flowList, childColumnList, searchSchemas, columnOptions } = toRefs(state);
const [registerSearchForm, { updateSchema, resetFields, submit: searchFormSubmit, getFormModel }] = useForm({
  baseColProps: { span: 6 },
  showActionButtonGroup: true,
  showAdvancedButton: true,
  compact: true,
});
const [
  registerTable,
  {
    reload,
    setLoading,
    insertTableDataRecord,
    updateTableDataRecord,
    deleteTableDataRecord,
    getFetchParams,
    getSelectRowKeys,
    getSelectRows,
    redoHeight,
    clearSelectedRowKeys,
    getDataSource,
  },
] = useTable({
  api: getModelList,
  immediate: false,
  clickToRowSelect: false,
  // scroll: { x: 'max-content' },
  afterFetch: data => {
    // 行内编辑
    if (state.columnData.type === 4) {
      const list = data.map(o => ({ ...o, rowEdit: false }));
      state.cacheList = cloneDeep(list);
      return list;
    }
    let list = data.map(o => ({
      ...o,
      ...state.expandObj,
    }));
    state.cacheList = cloneDeep(list);
    // 分组表格
    if (state.columnData.type === 3) {
      list.map(o => {
        if (o.children && o.children.length) {
          o.children = o.children.map(e => ({
            ...e,
            ...state.expandObj,
          }));
        }
      });
    }
    nextTick(() => {
      if (state.columnData.funcs?.afterOnload) setTableLoadFunc();
    });
    return list;
  },
});

const getPagination = computed(() => {
  if ([3, 5].includes(state.columnData.type) || !state.columnData.hasPage) return false;
  return { pageSize: state.columnData.pageSize };
});
const getChildTableStyle = computed(() => (state.columnData.type == 3 || state.columnData.type == 5 ? 1 : state.columnData.childTableStyle));
const getColumns = computed(() => (unref(getChildTableStyle) == 2 || state.columnData.type == 4 ? state.columns : state.complexColumns));
const getTableBindValue = computed(() => {
  let columns = unref(getColumns);
  if (state.config.enableFlow) columns.push({ title: '状态', dataIndex: 'flowState', width: 100 });
  const data: any = {
    pagination: unref(getPagination),
    searchInfo: unref(searchInfo),
    defSort: {
      sort: state.columnData.sort,
      sidx: state.columnData.defaultSidx,
    },
    columns,
    clearSelectOnPageChange: true,
    isTreeTable: [3, 5].includes(state.columnData.type),
    bordered: (unref(getChildTableStyle) != 2 && !!state.childColumnList?.length) || !!state.columnData.complexHeaderList?.length,
  };

  if (state.customRow) data.customRow = state.customRow;
  return data;
});
const getSummaryColumn = computed(() => {
  let defaultColumns = unref(getColumns);
  // 处理列固定
  if (state.columnSettingList?.length) {
    for (let i = 0; i < defaultColumns.length; i++) {
      inner: for (let j = 0; j < state.columnSettingList.length; j++) {
        if (defaultColumns[i].dataIndex === state.columnSettingList[j].dataIndex) {
          defaultColumns[i].fixed = state.columnSettingList[j].fixed;
          defaultColumns[i].visible = state.columnSettingList[j].visible;
          break inner;
        }
      }
    }
    defaultColumns = defaultColumns.filter(o => o.visible);
  }
  let columns: any[] = [];
  for (let i = 0; i < defaultColumns.length; i++) {
    const e = defaultColumns[i];
    if (e.jnpfKey === 'table' || e.jnpfKey === 'complexHeader') {
      if (e.children?.length) columns.push(...e.children);
    } else {
      columns.push(e);
    }
    if (e.fixed && e.children?.length) {
      for (let j = 0; j < e.children.length; j++) {
        e.children[j].fixed = e.fixed;
      }
    }
  }
  const leftFixedList = columns.filter(o => o.fixed === 'left');
  const rightFixedList = columns.filter(o => o.fixed === 'right');
  const noFixedList = columns.filter(o => o.fixed !== 'left' && o.fixed !== 'right');
  return [...leftFixedList, ...noFixedList, ...rightFixedList];
});
// 列表合计
const getColumnSum = computed(() => {
  const sums: any[] = [];
  const isSummary = key => state.columnData.summaryField.includes(key);
  const useThousands = key => unref(getSummaryColumn).some(o => o.__vModel__ === key && o.thousands);
  unref(getSummaryColumn).forEach((column, index) => {
    let sumVal = state.cacheList.reduce((sum, d) => sum + getCmpValOfRow(d, column.prop), 0);
    if (!isSummary(column.prop)) sumVal = '';
    sumVal = Number.isNaN(sumVal) ? '' : sumVal;
    const realVal = sumVal && !Number.isInteger(sumVal) ? Number(sumVal).toFixed(2) : sumVal;
    sums[index] = useThousands(column.prop) ? thousandsFormat(realVal) : realVal;
  });
  if ([1, 2].includes(state.columnData.type) && unref(getChildTableStyle) === 2 && state.childColumnList.length) sums.unshift('');
  return sums;
});

let relationData = {};

const handleSetRelationData = (e: any) => {
  relationData = e;
};

function getCmpValOfRow(row, key) {
  const isSummary = key => state.columnData.summaryField.includes(key);
  if (!state.columnData.summaryField.length || !isSummary(key)) return 0;
  const target = row[key];
  if (!target) return 0;
  const data = isNaN(target) ? 0 : Number(target);
  return data;
}
function getSummaryCellAlign(index) {
  if (!unref(getSummaryColumn).length) return;
  return unref(getSummaryColumn)[index]?.align || 'left';
}

function handleBatchFunc() {
  const ids = getSelectRowKeys();
  const id = ids.join('_');
  getModelInfo(props.modelId, id).then(res => {
    const dataForm = res.data || {};
    console.log(dataForm);
  });
}
function handleShowBrowse(id) {
  openPrintBrowse(true, { id, batchIds: getSelectRowKeys().join() });
}

// 顶部按钮点击事件
function headBtnsHandle(key, item) {
  const data = basicFormRef.value.getFormModel()
  if (data.CustomerID) {
    item.onClick(item.tar);
  } else {
    createMessage.error("请选择用户");
  }
}

// 头部自定义按钮点击事件 add by harry
function customHeadBtnsHandle(item) {
  console.log('独立功能');

  var firstRow = {};

  if (basicFormRef.value) {
    firstRow = basicFormRef.value.getFormModel();
  }

  // if (true) {
  //   var dataList = getDataSource();
  //   if (dataList.length > 0) {
  //     firstRow = dataList[0];
  //     //createMessage.success('请选择批量操作的数据');
  //     //return;
  //   }
  //   //可能存在group数据，需要取分组下的数据
  //   if ('children' in firstRow) {
  //     firstRow = firstRow.children[0];
  //   }
  //   console.log(firstRow);
  // }

  if (item.event.btnType == 1) {
    //如存在id，则会导致做为编辑传入。
    firstRow.id = '';
    handlePopup(item.event, firstRow);
  }
  if (item.event.btnType == 2) {
    handleScriptFunc(item.event, firstRow, 0);
  }
  if (item.event.btnType == 3) {
    handleInterface(item.event, firstRow);
  }
}

function handlePopup(item, record) {
  const data = {
    ...item,
    recordModelId: props.modelId,
    record: toRaw(record),
    isPreview: props.isPreview,
    webType: state.config.webType,
  };

  console.log(data);
  customFormRef.value?.init(data);
}

function handleInterface(item, record) {
  const handlerData = () => {
    getModelInfo(props.modelId, record.id).then(res => {
      const dataForm = res.data || {};
      if (!dataForm.data) return;
      //modify by harry 支持ids
      const data = { ...JSON.parse(dataForm.data), id: record.id, ids: record.ids };
      handlerInterface(data);
    });
  };
  const handlerInterface = data => {
    if (item.templateJson && item.templateJson.length) {
      item.templateJson.forEach(e => {
        e.defaultValue = e.sourceType == 1 ? data[e.relationField] || '' : e.relationField;
      });
    }
    const query = { paramList: item.templateJson || [] };
    getDataInterfaceRes(item.interfaceId, query).then(res => {
      createMessage.success(res.msg);

      if (item.afterType == '1') {
        reload();
      } else if (item.afterType == '2') {
        emit('reload');
      } else {
      }
    });
  };
  const handleFun = () => {
    state.config.webType == '4' ? handlerInterface(record) : handlerData();
  };
  if (!item.useConfirm) return handleFun();

  createConfirm({
    iconType: 'warning',
    title: t('common.tipTitle'),
    content: item.confirmTitle || '确认执行此操作?',
    onOk: () => {
      handleFun();
    },
  });
}
function init() {
  state.config = {
    modelId: props.modelId,
    isPreview: props.isPreview,
    ...props.config,
  };
  searchInfo.modelId = props.modelId;
  searchInfo.menuId = route.meta.modelId as string;
  if (props.isPreview) searchInfo.menuId = '270579315303777093';
  if (!state.config.columnData || (state.config.webType != '4' && !state.config.formData)) return;
  state.columnData = JSON.parse(state.config.columnData);
  if (state.columnData.type === 3) {
    state.columnData.columnList = state.columnData.columnList.filter(o => o.prop != state.columnData.groupField);
  }
  if (state.config.enableFlow == 1 && state.config.flowId) getFlowOptions();
  state.hasBatchBtn = state.columnData.btnsList.some(o => ['batchRemove', 'batchPrint'].includes(o.value));

  state.formConf = JSON.parse(state.config.formData);
  const customBtnsList = state.columnData.customBtnsList || [];
  const columnBtnsList = state.columnData.columnBtnsList || [];
  getColumnBtnsList(columnBtnsList, customBtnsList);
  state.columnOptions = state.columnData.columnOptions || [];

  if (!unref(getPagination)) (searchInfo as any).pageSize = 1000000;

  //add by harry 独立按钮增加
  state.customBtnsList
    .filter(o => o.eventType == 3 || o.eventType == 2)
    .forEach(item => {
      //独立事件
      state.columnData.btnsList.push({
        icon: 'icon-ym icon-ym-btn-add',
        label: item.label,
        onClick: customHeadBtnsHandle.bind(null, item),
        tar: item,
      });
    });
  //end

  setLoading(true);
  if (state.columnData.funcs.rowStyle) {
    state.customRow = (record, index) => {
      const data = { row: record, rowIndex: index };
      const func: any = getScriptFunc(state.columnData.funcs.rowStyle);
      const style: any = func ? func(data) : null;
      if (!style) return {};
      return { style };
    };
  }
  if (state.columnData.funcs.cellStyle) {
    state.customCell = (record, rowIndex, column) => {
      const data = { row: record, rowIndex, column, columnIndex: column.key };
      const func: any = getScriptFunc(state.columnData.funcs.cellStyle);
      const style: any = func ? func(data) : null;
      if (!style) return {};
      return { style };
    };
  }
  getSearchSchemas();
  getColumnList();
  if (state.columnData.type == 4) buildOptions();
  if (props.isPreview) return setLoading(false);
  if (state.columnData.type === 2) {
    state.treeFieldNames.key = state.columnData.treePropsValue || 'id';
    state.treeFieldNames.title = state.columnData.treePropsLabel || 'fullName';
    state.treeFieldNames.children = state.columnData.treePropsChildren || 'children';
    getTreeView(true);
  } else {
    nextTick(() => {
      state.columnData.searchList?.length ? searchFormSubmit() : reload({ page: 1 });
    });
  }
}

function getColumnBtnsList(columnBtnsList, customBtnsList) {
  if (props.isPreview || !state.columnData.useBtnPermission) {
    state.columnBtnsList = columnBtnsList;
    state.customBtnsList = customBtnsList;
  } else {
    let btns: any[] = [];
    let customBtns: any[] = [];
    // 过滤权限
    const permissionList = userStore.getPermissionList;
    const list = permissionList.filter(o => o.modelId === searchInfo.menuId);
    const perBtnList = list[0] && list[0].button ? list[0].button : [];
    for (let i = 0; i < columnBtnsList.length; i++) {
      inner: for (let j = 0; j < perBtnList.length; j++) {
        if ('btn_' + columnBtnsList[i].value === perBtnList[j].enCode) {
          btns.push(columnBtnsList[i]);
          break inner;
        }
      }
    }
    for (let i = 0; i < customBtnsList.length; i++) {
      inner: for (let j = 0; j < perBtnList.length; j++) {
        if (customBtnsList[i].value === perBtnList[j].enCode) {
          customBtns.push(customBtnsList[i]);
          break inner;
        }
      }
    }
    state.columnBtnsList = btns;
    state.customBtnsList = customBtns;
  }
}
function getSearchSchemas() {
  if (state.columnData.treeRelation) {
    for (let i = 0; i < state.columnData.columnOptions.length; i++) {
      const e = state.columnData.columnOptions[i];
      if (e.id === state.columnData.treeRelation) {
        state.treeRelationObj = { ...e, searchMultiple: false, jnpfKey: e.__config__.jnpfKey };
        break;
      }
    }
  }
  const schemas = getSearchFormSchemas(state.columnData.searchList);
  schemas.forEach(cur => {
    const config = cur.__config__;
    if (dyOptionsList.includes(config.jnpfKey)) {
      if (config.dataType === 'dictionary' && config.dictionaryType) {
        baseStore.getDicDataSelector(config.dictionaryType).then(res => {
          updateSchema([{ field: cur.field, componentProps: { options: res } }]);
        });
      }
      if (config.dataType === 'dynamic' && config.propsUrl) {
        const query = { paramList: config.templateJson || [] };
        getDataInterfaceRes(config.propsUrl, query).then(res => {
          const data = Array.isArray(res.data) ? res.data : [];
          updateSchema([{ field: cur.field, componentProps: { options: data } }]);
        });
      }
    }
    if ((Array.isArray(cur.value) && cur.value.length) || cur.value || cur.value === 0 || cur.value === false) cur.defaultValue = cur.value;
  });
  state.searchSchemas = schemas;
}
function getColumnList() {
  let columnList: any[] = [];
  if (props.isPreview || !state.columnData.useColumnPermission) {
    columnList = state.columnData.columnList;
  } else {
    // 过滤权限
    const permissionList = userStore.getPermissionList;
    const list = permissionList.filter(o => o.modelId === searchInfo.menuId);
    const perColumnList = list[0] && list[0].column ? list[0].column : [];
    for (let i = 0; i < state.columnData.columnList.length; i++) {
      inner: for (let j = 0; j < perColumnList.length; j++) {
        if (state.columnData.columnList[i].prop === perColumnList[j].enCode) {
          columnList.push(state.columnData.columnList[i]);
          break inner;
        }
      }
    }
  }
  let columns = columnList.map(o => ({
    ...o,
    title: o.label,
    dataIndex: o.prop,
    align: o.align,
    fixed: o.fixed == 'none' ? false : o.fixed,
    sorter: o.sortable,
    width: o.width || 100,
    customCell: state.customCell || null,
  }));
  if (state.columnData.type !== 3 && state.columnData.type !== 5) columns = getComplexColumns(columns);
  state.columns = columns.filter(o => o.prop.indexOf('-') < 0);
  if (state.columnData.type == 4) buildRowRelation();
  getChildComplexColumns(columns);
}
function getComplexColumns(columns) {
  let complexHeaderList: any[] = state.columnData.complexHeaderList || [];
  if (!complexHeaderList.length) return columns;
  let childColumns: any[] = [];
  for (let i = 0; i < complexHeaderList.length; i++) {
    const e = complexHeaderList[i];
    e.title = e.fullName;
    e.align = e.align;
    e.dataIndex = e.id;
    e.prop = e.id;
    e.children = [];
    e.jnpfKey = 'complexHeader';
    if (e.childColumns?.length) {
      childColumns.push(...e.childColumns);
      for (let k = 0; k < e.childColumns.length; k++) {
        const item = e.childColumns[k];
        for (let j = 0; j < columns.length; j++) {
          const o = columns[j];
          if (o.__vModel__ == item && o.fixed !== 'left' && o.fixed !== 'right' && !o.__config__.isSubTable) e.children.push({ ...o });
        }
      }
    }
  }
  complexHeaderList = complexHeaderList.filter(o => o.children.length);
  for (let i = 0; i < columns.length; i++) {
    const item = columns[i];
    if (!childColumns.includes(item.__vModel__) || item.__config__.isSubTable) complexHeaderList.push(item);
  }
  return complexHeaderList;
}
function getChildComplexColumns(columnList) {
  let list: any[] = [];
  for (let i = 0; i < columnList.length; i++) {
    const e = columnList[i];
    if (!e.prop.includes('-')) {
      list.push(e);
    } else {
      let prop = e.prop.split('-')[0];
      let vModel = e.prop.split('-')[1];
      let label = e.label.split('-')[0];
      let childLabel = e.label.replace(label + '-', '');
      let newItem = {
        align: 'center',
        jnpfKey: 'table',
        prop,
        label,
        title: label,
        dataIndex: prop,
        children: [],
        customCell: state.customCell || null,
      };
      e.dataIndex = vModel;
      e.title = childLabel;
      if (!state.expandObj.hasOwnProperty(`${prop}Expand`)) state.expandObj[`${prop}Expand`] = false;
      if (!list.some(o => o.prop === prop)) list.push(newItem);
      for (let i = 0; i < list.length; i++) {
        if (list[i].prop === prop) {
          list[i].children.push(e);
          break;
        }
      }
    }
  }

  getExportList(list);
  state.complexColumns = list;
  state.childColumnList = list.filter(o => o.jnpfKey === 'table');
  // 子表分组展示宽度取100
  if (unref(getChildTableStyle) !== 2) {
    for (let i = 0; i < state.childColumnList.length; i++) {
      const e = state.childColumnList[i];
      if (e.children?.length) e.children = e.children.map(o => ({ ...o, width: 100 }));
    }
  }
}
function getExportList(list) {
  let exportList: any[] = [];
  for (let i = 0; i < list.length; i++) {
    if (list[i].jnpfKey === 'table') {
      if (state.columnData.type != 4) exportList.push(...list[i].children);
    } else if (list[i].jnpfKey === 'complexHeader') {
      exportList.push(...list[i].children);
    } else {
      exportList.push(list[i]);
    }
  }
  state.exportList = exportList;
}
function setTableLoadFunc() {
  const parameter = { data: state.cacheList, tableRef: tableRef.value, onlineUtils };
  const func: any = getScriptFunc(state.columnData.funcs.afterOnload);
  if (!func) return;
  func(parameter);
}
function toggleExpand(row, field) {
  row[field] = !row[field];
}

function handleColumnChange(data) {
  state.columnSettingList = data;
}

function handleSearchSubmit(data) {
  // add by he 搜索的时候判断必填项
  const list = JSON.parse(state.config.columnData).searchList;
  const tar = list.find(item => {
    if (item.isRequire && !data[item.__vModel__]) {
      return true;
    } else {
      return false;
    }
  });

  if (tar) {
    createMessage.info('请填写' + tar.label);
    setLoading(false);
    return false;
  }
  // end

  if (Object.keys(relationData).length) {
    Object.keys(relationData).map(item => {
      data[item] = relationData[item];
      return item;
    });
  }

  clearSelectedRowKeys();
  let obj = {};
  for (let [key, value] of Object.entries(data)) {
    if (value) {
      if (Array.isArray(value)) {
        if (value.length) obj[key] = value;
      } else {
        obj[key] = value;
      }
    }
  }
  obj = { ...obj, ...(state.treeQueryJson || {}) };
  searchInfo.queryJson = JSON.stringify(obj) === '{}' ? '' : JSON.stringify(obj);
  reload({ page: 1 });

  // add by he
  if (data.CustomerID) {
    defaultValue = data.CustomerID

    onlineUtils.request('/api/ZX_Water/Payment/GetPayInfo?customerId=' + defaultValue, 'post', { customerId: defaultValue }).then(res => {
      const tar = res.data


      dataForm.customerCode = tar.customerCode
      dataForm.customerName = tar.customerName
      dataForm.mobilePhone = tar.mobilePhone
      dataForm.address = tar.address
      dataForm.factoryNum = tar.factoryNum
      dataForm.comment = tar.comment

      dataForm.actualAmount = String(tar.actualAmount)
      dataForm.arrears = String(tar.arrears)
      dataForm.overdueAmount = String(tar.overdueAmount)
      dataForm.perviousBalance = String(tar.perviousBalance)
      dataForm.receivableAmount = String(tar.receivableAmount)

    })
  }
  // end
}
function handleSearchReset() {
  searchFormSubmit();
}
function handleRowForm(record) {
  let fields: any[] = [];
  for (let i = 0; i < unref(getColumns).length; i++) {
    const e = unref(getColumns)[i];
    if (e.children?.length) {
      for (let j = 0; j < e.children.length; j++) {
        const o = e.children[j];
        o.__config__.span = 24;
        o.__config__.label = o.label;
        fields.push(toRaw(o));
      }
    } else {
      e.__config__.span = 24;
      e.__config__.label = e.label;
      fields.push(toRaw(e));
    }
  }
  fields = fields.map(o => {
    if (o.__config__?.templateJson && o.__config__?.templateJson.length) {
      o.__config__.templateJson = o.__config__.templateJson.map(o => ({ ...o, relationField: '' }));
    }
    if (o.templateJson && o.templateJson.length) {
      o.templateJson = o.templateJson.map(o => ({ ...o, relationField: '' }));
    }
    return o;
  });
  const formConf = { ...state.formConf, fields, popupType: 'general' };
  const data = {
    id: record.id,
    formConf,
    modelId: props.modelId,
    isPreview: props.isPreview,
    useFormPermission: state.columnData.useFormPermission,
    showMoreBtn: false,
    menuId: searchInfo.menuId,
    allList: state.cacheList,
    formData: record,
  };
  formRef.value?.init(data);
}

// 选择候选人
function submitCandidate(data) {
  saveForRowEdit(state.currRow, '0', data);
}
// 高级查询
function handleSuperQuery(superQueryJson) {
  if (props.isPreview) return;
  searchInfo.superQueryJson = superQueryJson;
  reload({ page: 1 });
}

function handleDownload(data) {
  if (props.isPreview) {
    setExportModalProps({ confirmLoading: false });
    createMessage.warning('功能预览不支持数据导出');
    return;
  }
  let query = { ...getFetchParams(), ...data };
  exportModel(props.modelId, query)
    .then(res => {
      setExportModalProps({ confirmLoading: false });
      if (!res.data.url) return;
      downloadByUrl({ url: res.data.url });
      closeExportModal();
    })
    .catch(() => {
      setExportModalProps({ confirmLoading: false });
    });
}

onMounted(() => {
  getType().then((res: any) => {
    tabArr.value = res.data;
    console.log(res.data);
    typeId = res.data.length && res.data[0].f_id;
    handleSwitch(typeId);
  });

  init();
});
</script>

<style lang="less" scoped>
:deep(.ant-table-title) {
  display: none !important;
}

.a-box-info {
  background-color: #fff;

}

.a-box-button {
  background-color: #fff;
  padding: 12px 0px 0px 15px;
}

.jnpf-content-wrapper-content {
  background-color: #fff;
  padding-left: 1px;
}

:deep(.labelRed .ant-form-item-label) {
  border-top: 1px solid #d9d9d9;
  border-left: 1px solid #d9d9d9;
  border-bottom: 1px solid #d9d9d9;
  box-sizing: border-box;
  background-color: #fafafa;
  height: 32px;
}

:deep(.labelRed label) {
  font-weight: bold;
  line-height: 32px;
  display: inline-block;
  color: #000 !important;
}

:deep(.labelRed input) {
  color: #ff0000;
  font-weight: bold;
  height: 32px;
  line-height: 32px;
  font-size: 1.3em;
}

.ant-form .ant-form-item
{
  margin-bottom:10px;
}

.ant-tabs-nav {
    margin: 0px;
}
.tabs {
  padding-left: 15px;
  padding-right: 15px;
}
:deep(.ant-tabs-nav) {
  margin-bottom: 0!important;
}
</style>